import { ResPool } from "./utils/ResPool";
import Enemy1 from "./Enemy1";
import Player from "./Player";
import Bullet from "./Bullet";
import { ColliderGroups } from "./constants/Enums";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Game extends cc.Component {
    pool:ResPool = null;
    /**
     * 玩家预制件.
     */
    @property(cc.Prefab)
    playerPrefab:cc.Prefab = null;

    /**
     * 敌机1预制件.
     */
    @property(cc.Prefab)
    emeny1Prefab:cc.Prefab = null;

    /**
     * 子弹预制件.
     */
    @property(cc.Prefab)
    bulletPrefab:cc.Prefab = null;

    /**
     * 得分标签.
     */
    @property(cc.Label)
    lbl_score:cc.Label = null;
    
    @property(cc.Node)
    btn_again:cc.Node=null;

    /**
     * 得分
     */
    score = 0;

    /**
     * 敌机数量.
     */
    enemy1Count = 0;
    /**
     * 场上最大敌机数量
     */
    MAX_ENEMY_COUNT = 8;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        //维护一个对象池.
        this.pool = new ResPool();
        
        //全局开启碰撞检测系统.
        let manager = cc.director.getCollisionManager();
        manager.enabled = true;//开启碰撞检测系统
        // manager.enabledDebugDraw = true;//开启 debug 绘制
    }
    
    start () {
        cc.director.pause();
    }

    update (dt) {
        //如果场上的敌机少于多少,则开始刷新敌机.
        if(this.enemy1Count< this.MAX_ENEMY_COUNT){
            this.spawnNewEnemy1();
        }
    }
    // LIFE-CYCLE CALLBACKS END
    spawnNewPlayer(){
        //初始化玩家.
        let player = this.pool.getPlayer();
        player.group = ColliderGroups.Player;
        //添加到场景.
        this.node.addChild(player);
        //保存到Game对象中.
        let script = player.getComponent(Player);
        script.game = this;
        script.init();
    }

    spawnNewEnemy1(){
        let enemy1 = this.pool.getEnemy1();
        // 添加到场景.
        enemy1.parent = this.node;
        enemy1.group = ColliderGroups.Enemy;
        //启动脚本
        let script = enemy1.getComponent(Enemy1);
        script.game = this;
        script.init();
        
        this.enemy1Count ++;
    }

    gainScore(){
        this.score ++;
        this.lbl_score.string = `Score: ${this.score}`;
    }

    reset(){
        //删除场景里现有的飞机,子弹.
        this.node.getComponentsInChildren(Player).forEach(elem=>elem.recycle());
        this.node.getComponentsInChildren(Enemy1).forEach(elem=>elem.recycle());
        this.node.getComponentsInChildren(Bullet).forEach(elem=>elem.recycle());
        
        this.enemy1Count = 0;
        // this.pool.clear();
    }

    gameStart(){
        this.btn_again.active = false;
        this.spawnNewPlayer();
        cc.director.resume();
    }

    gameOver(){
        this.reset();//销毁节点并不会立刻发生，而是在当前 帧逻辑更新结束后，统一执行。

        this.node.stopAllActions();
        cc.director.pause();
        this.btn_again.active = true;
    }
}
